const express = require("express");
const multiparty = require("multiparty");
const router = express.Router();
const fs = require("fs");
const { URL } = require("../../config/keys");
// 上传图片
router.post("/files/:location", (req, res) => {
  console.log(req.body);
  if (!req.params.location) {
    return res.json({
      success: false,
      msg: "上传失败，丢失location"
    });
  } else {
    fs.stat(`static/img/${req.params.location}`, (err, stats) => {
      if (err) {
        fs.mkdir(
          `static/img/${req.params.location}`,
          {
            recursive: true
          },
          err => {
            if (err) throw err;
          }
        );
      }
      var form = new multiparty.Form();
      form.uploadDir = `static/img/${req.params.location}`;
      form.parse(req, function (err, fields, files) {
        if (err) {
          return res.json({
            success: false,
            msg: "上传失败"
          });
        }
        console.log(files, '123123')
        try {
          var path
          if (files.url) {
            path = files.url[0].path.split("\\");
            path = path.join("/");
            var result = URL + path;
            return res.json({
              success: true,
              url: result
            });
          } else {
            path = files.screen[0].path.split("\\");
            path = path.join("/");
            var result = URL + path;
            return res.json([{ url: result }]);
          }


        } catch (e) {
          return res.json({
            success: false,
            msg: "上传失败了"
          });
        }
      });
    });
  }
});

module.exports = router;
